// pages/boughtItems/boughtItems.js
// pages/soldItems/soldItems.js
Page({
    data: {
        currentTab: 0, // 当前选中的标签索引
        statusTitles: ['待付款', '待发货', '待收货', '已完成','已退款'],
        statusValues: [1, 2, 3, 4,5], // 对应订单状态值
        orderList: [
            [],
            [],
            [],
            [],
            [],
        ], // 按状态分类的订单列表
        isLoading: [true, true, true, true,true], // 各状态加载状态
        hasMore: [true, true, true, true,true], // 各状态是否有更多数据
        pageNum: [1, 1, 1, 1,1], // 各状态当前页码
        pageSize: 10, // 每页显示数量
        userId: '' // 当前用户ID
    },

    onLoad(options) {
        // 获取当前用户ID
        const userInfo = wx.getStorageSync('userInfo');
        if (!userInfo) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            wx.navigateTo({
                url: '/pages/login/login'
            });
            return;
        }

        this.setData({
            userId: userInfo._id
        });

        // 加载各状态订单
        this.loadOrderList(0);
    },
    // 切换标签
    switchTab(e) {
        console.log(e);
        const index = e.currentTarget.dataset.index;
        this.setData({
            currentTab: Number(index)
        });
        console.log(index);
        this.loadOrderList(index);
    },

    // 加载订单列表
    async loadOrderList(tabIndex) {
        try {
            this.setData({
                isLoading: this.data.isLoading.map((item, i) => i == tabIndex ? true : item)
            });

            const {
                userId,
                pageNum,
                pageSize,
                statusValues
            } = this.data;
            const status = statusValues[tabIndex];
            console.log(status);
            // 调用云函数获取订单列表
            const res = await wx.cloud.callFunction({
                name: 'queryOrdersList',
                data: {
                    type: 'buy', // 卖出的订单
                    userId: userId,
                    // userId: '0253ee36683566070042b1cc538e95f0',
                    status: status,
                    pageNum: pageNum[tabIndex],
                    pageSize: pageSize
                }
            });
            console.log(res);
            if (res.result.success) {
                res.result.orders.forEach(item => {
                    if (item.goodsInfo.goodsImage) {
                        let arr = item.goodsInfo.goodsImage.split(',')
                        item.Image = arr
                    }
                })
                const newOrderList = [...this.data.orderList[tabIndex], ...res.result.orders];
                const hasMore = res.result.orders.length >= pageSize;

                this.setData({
                    orderList: this.data.orderList.map((item, i) => i == tabIndex ? newOrderList : item),
                    hasMore: this.data.hasMore.map((item, i) => i == tabIndex ? hasMore : item),
                    pageNum: this.data.pageNum.map((item, i) => i == tabIndex ? item + 1 : item),
                    isLoading: this.data.isLoading.map((item, i) => i == tabIndex ? false : item)
                });
                console.log(this.data);
            } else {
                wx.showToast({
                    title: res.result.message || '加载失败',
                    icon: 'none'
                });
            }
        } catch (error) {
            console.error('加载订单失败:', error);
            wx.showToast({
                title: '系统错误，请重试',
                icon: 'none'
            });
            this.setData({
                isLoading: this.data.isLoading.map((item, i) => i == this.data.currentTab ? false : item)
            });
        }
    },

    // 下拉刷新
    onPullDownRefresh() {
        this.setData({
            pageNum: [1, 1, 1, 1,1],
            orderList: [
                [],
                [],
                [],
                [],
                []
            ],
            hasMore: [true, true, true, true, true]
        });

        this.loadOrderList(this.data.currentTab);
        wx.stopPullDownRefresh();
    },

    // 上拉加载更多
    onReachBottom() {
        if (this.data.hasMore[this.data.currentTab]) {
            this.loadOrderList(this.data.currentTab);
        }
    },

    // 查看订单详情
    viewOrderDetail(e) {
        const orderId = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/orderDetail/orderDetail?orderId=${orderId}`
        });
    },

    // 发货操作
    handleReceiveOrder(e) {
        console.log(e);
        const orderId = e.currentTarget.dataset.id;
        wx.showModal({
            title: '确认收货',
            content: '是否确认已收货？',
            success: (res) => {
                if (res.confirm) {
                    this.updateOrderStatus(orderId, 4); // 更新为已发货状态
                }
            }
        });
    },
    // 更新订单状态
    async updateOrderStatus(orderId, newStatus) {
        try {
            wx.showLoading({
                title: '处理中...'
            });

            await wx.cloud.callFunction({
                name: 'updateOrderStatus',
                data: {
                    orderId: orderId,
                    newStatus: newStatus,
                }
            }).then(res => {
                console.log(res);
                if (res.result.success) {
                    wx.hideLoading();
                    wx.showToast({
                        title: '操作成功',
                        icon: 'success'
                    });
                    this.setData({
                        pageNum: [1, 1, 1, 1, 1],
                        orderList: [
                            [],
                            [],
                            [],
                            [],
                            []
                        ],
                        hasMore: [true, true, true, true, true]
                    });
                    // 刷新当前状态订单列表
                    this.loadOrderList(this.data.currentTab);
                } else {
                    wx.showToast({
                        title: res.result.message || '加载失败',
                        icon: 'none'
                    });
                }
            });
        } catch (error) {
            wx.hideLoading();
            console.error('更新订单状态失败:', error);
            wx.showToast({
                title: '操作失败',
                icon: 'none'
            });
        }
    },
    // 退款操作
    handleRefundOrder(e) {
        console.log(e);
        const orderId = e.currentTarget.dataset.id;
        const orderPrice = e.currentTarget.dataset.price;
        wx.showModal({
            title: '退款',
            content: '是否确认退款？',
            success: (res) => {
                if (res.confirm) {
                    wx.navigateTo({
                        url: `/pages/refundOrder/refundOrder?orderId=${orderId}&orderPrice=${orderPrice}`
                    });
                }
            }
        });
    },

    //继续付款
    handleContinuePay(e) {
        console.log(e);
        const data = e.currentTarget.dataset.val
        wx.showModal({
            title: '继续付款',
            content: '是否确认继续付款？',
            success: (res) => {
                if (res.confirm) {
                    const orderId = data._id
                    const paymentData = data.paymentResult.result.data;
                    wx.requestPayment({
                        timeStamp: paymentData?.timeStamp,
                        nonceStr: paymentData?.nonceStr,
                        package: paymentData?.packageVal,
                        paySign: paymentData?.paySign,
                        signType: 'RSA', // 该参数为固定值
                        success: (res) => {
                            console.log('支付成功:', res);
                            wx.showToast({
                                title: '支付成功',
                                icon: 'none'
                            });
                            wx.cloud.callFunction({
                                // 云函数名称
                                name: 'payNotify',
                                data: {
                                    goodsId: data.goodsId,
                                },
                            }).then(res => {
                                console.log(res);
                                // wx.navigateTo({
                                //     url: `/pages/orderSuccess/orderSuccess?orderId=${orderId}`
                                // })
                            }).catch(err => {
                                console.error('更新失败', err);
                            })
                            // 支付成功后更新订单状态
                            this.updateOrderStatus(orderId, 2); // 更新为待发货状态
                        },
                        fail: (err) => {
                            console.error('支付失败:', err);
                            wx.showToast({
                                title: '支付失败',
                                icon: 'none'
                            });
                        },
                        complete: () => {
                            // 无论成功失败都刷新订单列表
                            this.setData({
                                pageNum: [1, 1, 1, 1, 1],
                                orderList: [
                                    [],
                                    [],
                                    [],
                                    [],
                                    []
                                ],
                                hasMore: [true, true, true, true, true]
                            });
                            this.loadOrderList(this.data.currentTab);
                        }
                    });
                }
            }
        });
    }
});